﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _2.calculatorWindowsForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_input_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_cal_Click(object sender, EventArgs e)
        {
            string equation = textBox1_input.Text;
            int pos = 0, notation = -1;
            int num1 = 0, num2 = 0;
            // 获得第一个数
            while (pos < equation.Length && '0' <= equation[pos] && equation[pos] <= '9')
            {
                num1 = num1 * 10 + equation[pos] - '0';
                pos++;
            }

            // 获取符号
            while (pos < equation.Length && (equation[pos] < '0' || equation[pos] > '9'))
            {
                switch (equation[pos])
                {
                    case '+': notation = 0; break;
                    case '-': notation = 1; break;
                    case '*': notation = 2; break;
                    case '/': notation = 3; break;
                    default: break;
                }
                pos++;
            }

            //获取第二个数
            while (pos < equation.Length && '0' <= equation[pos] && equation[pos] <= '9')
            {
                num2 = num2 * 10 + equation[pos] - '0';
                pos++;
            }

            if (notation == -1 || (pos < equation.Length && equation[pos] != '=')) 
            {
                textBox_output.Text = "输入的等式有误！";
            }
            else
            {
                double ans = 0;
                switch (notation)
                {
                    case 0: ans = num1 + num2; break;
                    case 1: ans = num1 - num2; break;
                    case 2: ans = num1 * num2; break;
                    case 3: ans = num1 / (1.0 * num2); break;
                }

                textBox_output.Text = ("答案为：" + ans.ToString("0.#####"));
            }
        }
    }
}
